package service.impl;

import dao.DeviceDao;
import dao.UserLocationDao;
import domain.Device;
import domain.UserLocation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import service.ServiceResponse;
import service.SyncupService;

import java.util.Date;

/**
 * Created by chen<chen@youjianghr.com> on 2015/7/20.
 *
 * @author chen<chen@youjianghr.com>
 */
@Service
public class SyncupServiceImpl implements SyncupService {

    @Autowired
    private UserLocationDao userLocationDao;

    @Autowired
    private DeviceDao deviceDao;

    @Override
    @Transactional(readOnly = false)
    public ServiceResponse syncup(long userId, UserLocation userLocation, Device device) {

        Date now = new Date();

        UserLocation userLocationDB = userLocationDao.get(userId);
        if (userLocationDB == null) {
            userLocationDao.insert(userLocation);
        } else {
            userLocation.setId(userId);
            userLocation.setUpdateTime(now);
            userLocationDao.update(userLocation);
        }

        Device deviceDB = deviceDao.getByUserIdAndIMEI(userId, device.getImei());
        if (deviceDB == null) {
            device.setAccountId(userId);
            device.setLatestUse(now);

            deviceDao.insert(device);
        } else {
            deviceDao.updateLastUse(deviceDB.getId());
        }

        return ServiceResponse.success();
    }
}
